import React, { useState } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Rating,
  Stack,
  Avatar,
  Chip,
  IconButton,
  Menu,
  MenuItem,
  FormControl,
  Select,
  InputLabel,
  SelectChangeEvent,
} from '@mui/material';
import MoreVertIcon from '@mui/icons-material/MoreVert';
import ThumbUpIcon from '@mui/icons-material/ThumbUp';
import ThumbDownIcon from '@mui/icons-material/ThumbDown';

interface Review {
  id: number;
  gameTitle: string;
  gameCover: string;
  rating: number;
  content: string;
  date: string;
  likes: number;
  dislikes: number;
  helpful: number;
  recommended: boolean;
}

// Mock data
const mockReviews: Review[] = [
  {
    id: 1,
    gameTitle: "艾尔登法环",
    gameCover: "https://via.placeholder.com/100x100",
    rating: 4.5,
    content: "这是一款非常优秀的游戏，画面精美，战斗系统深度十足。虽然难度较高，但是非常有成就感。推荐给所有喜欢挑战的玩家。",
    date: "2023-12-20",
    likes: 42,
    dislikes: 3,
    helpful: 38,
    recommended: true,
  },
  // ... 更多评论数据
];

interface ReviewCardProps {
  review: Review;
  onDelete: (id: number) => void;
  onEdit: (id: number) => void;
}

const ReviewCard: React.FC<ReviewCardProps> = ({ review, onDelete, onEdit }) => {
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);

  const handleMenuOpen = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget);
  };

  const handleMenuClose = () => {
    setAnchorEl(null);
  };

  const handleEdit = () => {
    onEdit(review.id);
    handleMenuClose();
  };

  const handleDelete = () => {
    onDelete(review.id);
    handleMenuClose();
  };

  return (
    <Card sx={{ mb: 2 }}>
      <CardContent>
        <Stack direction="row" spacing={2}>
          <Avatar
            variant="rounded"
            src={review.gameCover}
            sx={{ width: 80, height: 80 }}
          />
          <Box sx={{ flex: 1 }}>
            <Stack
              direction="row"
              justifyContent="space-between"
              alignItems="flex-start"
            >
              <Box>
                <Typography variant="h6" gutterBottom>
                  {review.gameTitle}
                </Typography>
                <Stack direction="row" spacing={1} alignItems="center" sx={{ mb: 1 }}>
                  <Rating value={review.rating} precision={0.5} readOnly size="small" />
                  <Chip
                    label={review.recommended ? "推荐" : "不推荐"}
                    color={review.recommended ? "success" : "error"}
                    size="small"
                  />
                  <Typography variant="body2" color="text.secondary">
                    {review.date}
                  </Typography>
                </Stack>
              </Box>
              <IconButton onClick={handleMenuOpen}>
                <MoreVertIcon />
              </IconButton>
            </Stack>

            <Typography variant="body1" sx={{ mb: 2 }}>
              {review.content}
            </Typography>

            <Stack direction="row" spacing={2} alignItems="center">
              <Stack direction="row" spacing={1} alignItems="center">
                <IconButton size="small">
                  <ThumbUpIcon fontSize="small" />
                </IconButton>
                <Typography variant="body2">{review.likes}</Typography>
              </Stack>
              <Stack direction="row" spacing={1} alignItems="center">
                <IconButton size="small">
                  <ThumbDownIcon fontSize="small" />
                </IconButton>
                <Typography variant="body2">{review.dislikes}</Typography>
              </Stack>
              <Typography variant="body2" color="text.secondary">
                {review.helpful} 人觉得有帮助
              </Typography>
            </Stack>
          </Box>
        </Stack>
      </CardContent>

      <Menu
        anchorEl={anchorEl}
        open={Boolean(anchorEl)}
        onClose={handleMenuClose}
      >
        <MenuItem onClick={handleEdit}>编辑评论</MenuItem>
        <MenuItem onClick={handleDelete}>删除评论</MenuItem>
      </Menu>
    </Card>
  );
};

const Reviews: React.FC = () => {
  const [sortBy, setSortBy] = useState('date');
  const [reviews, setReviews] = useState(mockReviews);

  const handleSortChange = (event: SelectChangeEvent) => {
    setSortBy(event.target.value);
    // 根据选择的排序方式对评论进行排序
    const sorted = [...reviews].sort((a, b) => {
      switch (event.target.value) {
        case 'date':
          return new Date(b.date).getTime() - new Date(a.date).getTime();
        case 'rating':
          return b.rating - a.rating;
        case 'helpful':
          return b.helpful - a.helpful;
        default:
          return 0;
      }
    });
    setReviews(sorted);
  };

  const handleDeleteReview = (id: number) => {
    setReviews(reviews.filter(review => review.id !== id));
  };

  const handleEditReview = (id: number) => {
    // TODO: 实现编辑评论功能
    console.log('Edit review:', id);
  };

  return (
    <Box>
      <Stack
        direction="row"
        justifyContent="space-between"
        alignItems="center"
        sx={{ mb: 3 }}
      >
        <Typography variant="h6">
          我的评论 ({reviews.length})
        </Typography>
        <FormControl size="small" sx={{ minWidth: 120 }}>
          <InputLabel>排序方式</InputLabel>
          <Select
            value={sortBy}
            label="排序方式"
            onChange={handleSortChange}
          >
            <MenuItem value="date">最新</MenuItem>
            <MenuItem value="rating">评分</MenuItem>
            <MenuItem value="helpful">最有帮助</MenuItem>
          </Select>
        </FormControl>
      </Stack>

      {reviews.map((review) => (
        <ReviewCard
          key={review.id}
          review={review}
          onDelete={handleDeleteReview}
          onEdit={handleEditReview}
        />
      ))}
    </Box>
  );
};

export default Reviews;
